use crate::domain::categories::service;
use crate::extends::response;
use crate::extends::jwt::Claims;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json;
use tracing::info;
use jsonwebtoken::{TokenData};
use crate::extends::db::RB;
use bigdecimal::BigDecimal;
use chrono::NaiveDateTime;

use rbatis::core::value::DateTimeNow;
use rbatis::core::Error;
use rbatis::crud::{CRUDMut, CRUD, Skip};
use rbatis::rbatis::Rbatis;
use serde_json::{json,Value};
use rbatis::crud::CRUDTable;
use std::collections::HashMap;

#[fn_handler]
pub async fn categories(req: &mut Request, depot: &mut Depot, res: &mut Response) {

    let pageNumber =req.get_query::<u64>("pageNumber").unwrap();
    let pageSize =req.get_query::<u64>("pageSize").unwrap();
    let mut params = HashMap::new();
    params.insert("start".to_owned(),json!((pageNumber-1)*pageSize+1));
    params.insert("end".to_owned(),json!(pageNumber*pageSize));

    params.insert("categoryLevel".to_owned(),json!(req.get_query::<String>("categoryLevel").unwrap()));
    params.insert("parentId".to_owned(),json!(req.get_query::<String>("parentId").unwrap()));
    //begin
   let mut tx = RB.acquire_begin().await.unwrap();
   let result = service::findGoodsCategoryList(&mut tx,&params).await ;

   match result {
       Ok(su) => {

        let count = service::getTotalGoodsCategories(&mut tx,&params).await.unwrap().unwrap() ;
 
        let mut m =HashMap::new();
        m.insert("list",json!(&su.unwrap()));
        m.insert("totalCount",json!(&count));
        m.insert("currPage",json!(pageNumber));

        res.render_json(&response::success_result(m));
       }
       Err(err) => {
        res.render_json(&response::fail_result(err.to_string()));
       }
   }
    //commit or rollback
    tx.commit().await.unwrap();

}